package com.lagou.edu.filter;

import com.lagou.edu.service.UserFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 验证token是否有效
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String requestUrl = request.getURI().getRawPath();
//        String clientIp = request.getRemoteAddress().getHostString();

        if (requestUrl.startsWith("/api/user/info/")) {
            String[] split = requestUrl.split("/");
            ModelMap result = userFeignClient.getInfo(split[split.length - 1]);
            if (!result.get("code").toString().equals("200")) {
                // 拒绝访问，返回
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                log.debug("=====> 未检测到 token");
                String data = "Request be denied!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
